﻿using MediatR;
using PublicClass;
using S.Services.SheepMale.Domain.PurchaseSales;
using S.Services.SheepMale.Infrastructure;
using S.Services.SheepMale.Read.Api.Application.ReadCommand.ReadSheepMaleCommand;

namespace S.Services.SheepMale.Read.Api.Application.ReadCommandHandler.ReadSheepMaleCommandHandler
{
    public class PurchaseShowCommandHandler : IRequestHandler<PurchaseShowCommand, PageInfo<EntityPurchase>>
    {
        private readonly IRepository<EntityPurchase> repository;

        private readonly PageInfo<EntityPurchase> pageInfo;

        public PurchaseShowCommandHandler(IRepository<EntityPurchase> repository, PageInfo<EntityPurchase> pageInfo)
        {
            this.repository = repository;
            this.pageInfo = pageInfo;
        }

        public async Task<PageInfo<EntityPurchase>> Handle(PurchaseShowCommand request, CancellationToken cancellationToken)
        {
            var result = await repository.AllAsync();
            if (request.Sdate != null)
            {
                result = result.Where(x => x.PurDate >= request.Sdate);
            }
            if (request.Edate != null)
            {
                result = result.Where(x => x.PurDate <= request.Edate.Value.AddDays(1));
            }
            if (request.SheeTypeInfo != null)
            {
                result = result.Where(x => x.SheepTypeInfo == request.SheeTypeInfo);
            }
            if (request.Stash != null)
            {
                result = result.Where(x => x.Stash == request.Stash);
            }
            if (request.CottageName != null)
            {
                result = result.Where(x => x.CottageName == request.CottageName);
            }
            if (request.Earbugles != null)
            {
                result = result.Where(x => x.Earbugles.Contains(request.Earbugles));
            }
            if (request.Buyer != null)
            {
                result = result.Where(x => x.Buyer == request.Buyer);
            }
            if (request.DocumentNumber != null)
            {
                result = result.Where(x => x.DocumentNumber.Contains(request.DocumentNumber));
            }
            if (request.Supplier != null)
            {
                result = result.Where(x => x.Supplier == request.Supplier);
            }

            pageInfo.totalCount = result.Count();
            pageInfo.pageCount = (int)Math.Ceiling(pageInfo.totalCount * 1.0 / request.pageSize);
            pageInfo.datas = result.OrderByDescending(x => x.CreateDate).Skip((request.pageIndex - 1) * request.pageSize).Take(request.pageSize).ToList();
            return pageInfo;
        }
    }
}
